<template>
  <div>
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="handleDel">
          删除行
        </a-button>
        <!-- <a-button>
                    导出模板
                </a-button>
                <a-button>
                    导入
                </a-button> -->
      </template>
      <excel
        ref="exportSelect"
        file-name="评审意见表"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="评审意见表"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
      <!-- <a-button>
                打印
            </a-button> -->
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['orgName', 'jobName', 'employeeName','opinion','opinionDate']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="record.editable">
            <a-date-picker
              v-if="col === 'opinionDate'"
              v-model="opinionDate"
              value-format="YYYY-MM-DD"
              @change="e => handleChange(opinionDate, record.id, col)"
            />
            <BaseInput
              v-else
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record, index"
      >
        <div class="editable-row-operations">
          <span v-if="record.editable && state !== 3">
            <a @click="() => save(record.id)">保存</a>
            <a @click="() => cancel(record.id)">取消</a>
          </span>
          <span v-else>
            <a
              :disabled="editingKey !== ''"
              @click="() => edit(record.id)"
            >编辑</a>
          </span>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <!-- <material-list ref="detailDialog" @createList="createList"></material-list> -->
  </div>
</template>
<script>
   import {selectOption} from '@/api/material/goods/goods';
    import {opinionList,opinionListDel,opinionAdd,opinionEdit} from '@/api/material/procurement/review';
    import {columns} from './insideModel';
    const data = [];
    export default {
	name:'a'+Date.now(),
        name: 'RebarPlan',
        props: {
            state: {
                type: Number
            },
            id: {
                type: String
            }
        },
        data() {
            this.cacheData = data.map(item => ({...item}));
            return {
                selectedRows: [],
               pageNo:1,
                pageSize:10,
                queryParam: {},
                totalSize:0,
                selectedRowKeys:[],
                columns:columns,
                editingKey:'',
                data:[],
                optionArr:[],
                selectedId:[],
                selectVal:null,
                opinionDate:null,
                rules:{
                    orgName:{rule:'required',message:'评审层级不能为空'},
                    jobName:{rule:'required',message:'评审岗位不能为空'},
                    employeeName:{rule:'required',message:'评审人员不能为空'},
                    opinionDate:{rule:'required',message:'评审时间不能为空'},
                }
            }
        },
        watch: {
        },
        mounted:function () {
            this.getOption();
            if(this.state === 3){
                this.editingKey = true;
            }
            this.list();
            this.initErrMessage(this.rules);
            this.$refs.exportSelect.tableToExcelFile(this.$refs.table);
            this.$refs.exportAll.tableToExcelFile(this.$refs.table);
        },
        methods: {
            exportSelect: function () {
                if (this.selectedRowKeys.length > 0) {
                    this.$refs.exportSelect.setDataAndGenerate(this.selectedRows);
                } else {
                    this.$message.warning('请选择需要导出的数据');
                }
            },
            exportAll:function(){
                // 参数：查询条件、导出的回调
                if (this.totalSize){
                    this.pageNo = 1;
                    this.list(this.$refs.exportAll.setDataAndGenerate);
                }else {
                    this.$message.warning('没有可导出的数据');
                }
            },
            getOption:function () {
                let _this = this;
                selectOption({
                    type:0
                }).then(res => {
                    if (res.code === 200) {
                        _this.optionArr = res.data;
                    }
                })
            },
            openDailog:function () {
                // this.$refs.detailDialog.open();
                if(this.editingKey !== ''){
                    this.$message.error('新增前请结束当前操作行');
                    return;
                }
                this.opinionDate = null;
                let row = {orgName:'',jobName:null,employeeName:'',opinion:'',
                opinionDate:null,isAdd:true,editable:true,fileReviewId:this.id};
                this.data.unshift(row);
                this.editingKey = true;
            },
            // 删除
            handleDel() {
                this.delList(opinionListDel, ()=>{
                    this.initTable()
                    this.selectedId = [];
                    this.selectedRowKeys = [];
                    this.selectedRows = [];
                    this.editingKey = ''
                }, {ids: this.selectedId});
            },
            initTable() {
                this.pageNo = 1;
                this.list();
            },
            list(callback) {
                let _this = this;
                opinionList({pageSize: callback ? _this.totalSize : _this.pageSize, pageNo: _this.pageNo,fileReviewId:_this.id}).then(res => {
                    if (res.code === 200) {
                        if(callback){
                            if(res.data.length){
                                callback(res.data);
                            }else{
                                this.$message.warning('没有可导出的数据');
                            }
                            return;
                        }
                        _this.data = res.data;
                        _this.totalSize = res.totalSize;
                        this.cacheData = res.data.map(item => ({...item}));
                    }
                })
            },
            handleChange(value, key, column) {
                const newData = [...this.data];
                const target = newData.filter(item => key === item.id)[0];
                console.log(value);
                if (target) {
                    target[column] = value;
                    if(this.rules[column]){                       
                        this.customValidation(value,column);     
                    }  
                    this.data = newData;
                }
            },
            edit(key) {
                const newData = [...this.data];
                const target = newData.filter(item => key === item.id)[0];
                this.editingKey = key;
                if (target) {
                    target.editable = true;
                    this.data = newData;
                    console.log(target.editable);
                }
            },
            handlePageChange(pageNo, pageSize) {
                this.pageNo = pageNo;
                this.getTable()
            },
            showSizeChange(pageNo, pageSize) {
                this.pageSize = pageSize;
                this.initTable();
            },
            save(key) {
                // 编辑保存
                const newData = [...this.data];
                const newCacheData = [...this.cacheData];
                const target = newData.filter(item => key === item.id)[0];
                for(let key in target){
                    if(this.rules[key]){
                        this.customValidation(target[key],key);
                    }                  
                }         
                for(let i in this.customValidationErr){
                    if(i){
                        return;
                    }     
                }  
                if(target.isAdd){
                    opinionAdd(target).then(res => {
                        if (res.data.code === 200) {
                            this.$message.success('新增成功');
                            this.initTable()
                        }
                    });
                }else{
                    opinionEdit(target).then(res => {
                        if (res.code === 200) {
                            this.$message.success('编辑成功');
                            this.initTable()
                        }
                    });
                }
                const targetCache = newCacheData.filter(item => key === item.id)[0];
                if (target && targetCache) {
                    delete target.editable;
                    this.data = newData;
                    Object.assign(targetCache, target);
                    this.cacheData = newCacheData;
                }
                this.editingKey = '';
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.selectedId = [];
                selectedRows.map(i => {
                    this.selectedId.push(i.id)
                });
                this.selectedRowKeys = selectedRowKeys;
                this.selectedRows = selectedRows;
            },
            cancel(key) {
                const newData = [...this.data];
                const target = newData.filter(item => key === item.id)[0];
                this.editingKey = '';
                if (target) {
                    if(target.isAdd){
                        newData.splice(0,1);
                    }else{
                        Object.assign(target, this.cacheData.filter(item => key === item.id)[0]);
                        target.editable = false;
                        delete target.editable;                    
                    }
                    this.data = newData;
                }
            }
        }
    }
</script>
